/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pt.iasd.youthshelter.datacore.controller;

import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.openide.util.lookup.ServiceProvider;
import pt.iasd.youthshelter.datacore.EntityManagerSemaphore;
import pt.iasd.youthshelter.datacore.controller.exceptions.NonexistentEntityException;
import pt.iasd.youthshelter.datamodel.Role;
import pt.iasd.youthshelter.datamodel.Pathfinder;
import pt.iasd.youthshelter.datamodel.PathfinderRole;
import pt.iasd.youthshelter.datamodel.service.PathfinderRoleController;

/**
 *
 * @author Rui
 */
@ServiceProvider(service=PathfinderRoleController.class)
public class PathfinderRoleJpaController implements Serializable, PathfinderRoleController {

    private EntityManager aquireEntityManager() throws InterruptedException {
        EntityManagerSemaphore.getInstance().getSemaphore().acquire();
        return EntityManagerSemaphore.getInstance().getEntityManager();
    }
    
    private void releaseEntityManager(EntityManager em) {
        if (em != null && em.isOpen()) {
            em.close();
        }
        EntityManagerSemaphore.getInstance().getSemaphore().release();
    }

    @Override
    public void create(PathfinderRole pathfinderRole) {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            em.getTransaction().begin();
            Role roleId = pathfinderRole.getRoleId();
            if (roleId != null) {
                roleId = em.getReference(roleId.getClass(), roleId.getId());
                pathfinderRole.setRoleId(roleId);
            }
            Pathfinder pathfinderId = pathfinderRole.getPathfinderId();
            if (pathfinderId != null) {
                pathfinderId = em.getReference(pathfinderId.getClass(), pathfinderId.getId());
                pathfinderRole.setPathfinderId(pathfinderId);
            }
            em.persist(pathfinderRole);
            if (roleId != null) {
                roleId.getPathfinderRoleList().add(pathfinderRole);
                em.merge(roleId);
            }
            if (pathfinderId != null) {
                pathfinderId.getPathfinderRoleList().add(pathfinderRole);
                em.merge(pathfinderId);
            }
            em.getTransaction().commit();
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
    }

    @Override
    public void edit(PathfinderRole pathfinderRole) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            em.getTransaction().begin();
            PathfinderRole persistentPathfinderRole = em.find(PathfinderRole.class, pathfinderRole.getId());
            Role roleIdOld = persistentPathfinderRole.getRoleId();
            Role roleIdNew = pathfinderRole.getRoleId();
            Pathfinder pathfinderIdOld = persistentPathfinderRole.getPathfinderId();
            Pathfinder pathfinderIdNew = pathfinderRole.getPathfinderId();
            if (roleIdNew != null) {
                roleIdNew = em.getReference(roleIdNew.getClass(), roleIdNew.getId());
                pathfinderRole.setRoleId(roleIdNew);
            }
            if (pathfinderIdNew != null) {
                pathfinderIdNew = em.getReference(pathfinderIdNew.getClass(), pathfinderIdNew.getId());
                pathfinderRole.setPathfinderId(pathfinderIdNew);
            }
            pathfinderRole = em.merge(pathfinderRole);
            if (roleIdOld != null && !roleIdOld.equals(roleIdNew)) {
                roleIdOld.getPathfinderRoleList().remove(pathfinderRole);
                roleIdOld = em.merge(roleIdOld);
            }
            if (roleIdNew != null && !roleIdNew.equals(roleIdOld)) {
                roleIdNew.getPathfinderRoleList().add(pathfinderRole);
                em.merge(roleIdNew);
            }
            if (pathfinderIdOld != null && !pathfinderIdOld.equals(pathfinderIdNew)) {
                pathfinderIdOld.getPathfinderRoleList().remove(pathfinderRole);
                pathfinderIdOld = em.merge(pathfinderIdOld);
            }
            if (pathfinderIdNew != null && !pathfinderIdNew.equals(pathfinderIdOld)) {
                pathfinderIdNew.getPathfinderRoleList().add(pathfinderRole);
                em.merge(pathfinderIdNew);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = pathfinderRole.getId();
                if (findPathfinderRole(id) == null) {
                    throw new NonexistentEntityException("The pathfinderRole with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            releaseEntityManager(em);
        }
    }

    @Override
    public void destroy(Integer id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            em.getTransaction().begin();
            PathfinderRole pathfinderRole;
            try {
                pathfinderRole = em.getReference(PathfinderRole.class, id);
                pathfinderRole.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The pathfinderRole with id " + id + " no longer exists.", enfe);
            }
            Role roleId = pathfinderRole.getRoleId();
            if (roleId != null) {
                roleId.getPathfinderRoleList().remove(pathfinderRole);
                em.merge(roleId);
            }
            Pathfinder pathfinderId = pathfinderRole.getPathfinderId();
            if (pathfinderId != null) {
                pathfinderId.getPathfinderRoleList().remove(pathfinderRole);
                em.merge(pathfinderId);
            }
            em.remove(pathfinderRole);
            em.getTransaction().commit();
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
    }

    @Override
    public List<PathfinderRole> findPathfinderRoleEntities() {
        return findPathfinderRoleEntities(true, -1, -1);
    }

    @Override
    public List<PathfinderRole> findPathfinderRoleEntities(int maxResults, int firstResult) {
        return findPathfinderRoleEntities(false, maxResults, firstResult);
    }

    private List<PathfinderRole> findPathfinderRoleEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(PathfinderRole.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
        return null;
    }

    @Override
    public PathfinderRole findPathfinderRole(Integer id) {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            return em.find(PathfinderRole.class, id);
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
        return null;
    }

    @Override
    public int getPathfinderRoleCount() {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<PathfinderRole> rt = cq.from(PathfinderRole.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
        return 0;
    }
    
}
